﻿using System;
using System.Collections.Generic;
using UnityEngine;

public class CandidatesListVCData
{
    public List<CandidateVCData> candidates;
    public int defaultCandidate;
}

public class CandidateVCData
{
    public long candidateId;
    public bool unlock;
    public int price;
    public string name;
    public string location;
    public string job;
    public FiveDimensions fiveDimensions;
    public FiveDimensions require;
    public int result;
}

public class CandidatesListViewController : ViewController, ICandidatesListPanel
{
    private MBattleSceneController battleSceneController => GetComponentInParent<MBattleSceneController>();
    MBattleController battleScene =>battleSceneController .mBattleController;

    CandidatesListPanel m_Panel;
    public CandidatesListPanel panel => m_Panel;

    CandidatesListVCData m_Data;

    //int m_CurCandidateId;

    public CandidatesListPanel Init(CandidatesListVCData data)
    {
        if (m_Panel == null)
            m_Panel = InitUI();

        GameDebug.LogError($"data != null:{data != null}");

        m_Data = data;
        //m_CurCandidateId = data.defaultCandidate;
        m_Panel.Init(data);

        return m_Panel;
    }

    protected override void WillLoadView()
    {
        base.WillLoadView();
        
        //this.battleScene.ShowCandidateCam();

        var user = MGame.instance.MUser;
    }

    protected virtual CandidatesListPanel InitUI()
    {
        CandidatesListPanel prefab = ResourceManager.Load<CandidatesListPanel>(ViewPath.candidateListPanel);
        if (prefab == null)
        {
            GameDebug.LogError("skinsListPanel prefab null");
            return null;
        }
        m_Panel = GameObject.Instantiate<CandidatesListPanel>(prefab, transform);
        m_Panel.uiListener = this;
        m_Panel.SetViewController(this);
        // panel.name = "战斗UI";
        return m_Panel;
    }

    public void OnSelectCandidate(long skinId)
    {
        if (battleScene.skinId != skinId)
        {
            GameDebug.LogError($"选择皮肤：{skinId}");

            ChangePlayerCandidate(skinId, true);
        }
    }

    public const int applyPrice = 100;
    
    public void OnConfirm(long Id)
    {
        if (MGame.instance.MUser.coin < applyPrice)
        {
            MGame.instance.ShowNoticePanel(Localization.instance.GetValue("coin_not_enough"));
            return;
        }

        MGame.instance.MUser.AddCoin(-applyPrice);
        
        if (panel)
        {
            panel.RefreshMsg((int)Id,Apply.Applying);
        }
        
        DoActionDelay.DelayAction(2, () =>
        {
            int result = 0;   
            string refuseReason = "";
            
            List<FiveDimensionsType> unreachTypes = new List<FiveDimensionsType>();
            
            var candidate = ConstantData.instance.GetCandidate(Id);
            if (candidate != null)
            {
                var myFiveDimensions = MGame.instance.MUser.userInfo;
                var requirement = candidate.requirement;

                if (myFiveDimensions.height < requirement.Height)
                    unreachTypes.Add(FiveDimensionsType.Height);
                /*if (myFiveDimensions.Weight < requirement.Weight)
                    unreachTypes.Add(FiveDimensionsType.Weight);*/
                if (myFiveDimensions.income < requirement.Income)
                    unreachTypes.Add(FiveDimensionsType.Income);
                if (myFiveDimensions.eduation < requirement.Education)
                    unreachTypes.Add(FiveDimensionsType.Edu);
                
                /*var myScore = UIPropertyShow.GetScore(MGame.instance.MUser.fiveDimensions);
                 var cadidateScore = UIPropertyShow.GetCandidateScore(candidate.fiveDimensions);
 
                 int diff = myScore - cadidateScore;
                 int min = -10;
                 int max = 5;*/
#if  UNITY_EDITOR
    unreachTypes.Clear();            
#endif
                if (unreachTypes.Count <= 0)
                {
                    result = Apply.ApplyResult_Suc;
                    MGame.instance.MUser.AddApply(MGame.instance.MUser.id, Id, Apply.ApplyResult_Suc,"想和你认识一下~","",UnityFunctions.GetTimeStampSeconds());
                }
                else //if (diff < min)
                {
                    result = Apply.ApplyResult_Fail;
                    MGame.instance.MUser.AddApply(MGame.instance.MUser.id, Id, Apply.ApplyResult_Fail, "想和你认识一下~","",UnityFunctions.GetTimeStampSeconds());
                }
                /*else
                {
                    float rate = (float)(diff - min) / (max - min);
                    float rand = new RealRandom().Random(min, max);
                    float rateValue = Mathf.Lerp(min, max, rate);
                    Debug.Log($"win rate:{rate}  rand:{rand}  rateValue:{rateValue}");
                    if (rand > rateValue)
                    {
                        result = Apply.ApplyResult_Suc;
                        MGame.instance.MUser.AddApply(Id, Apply.ApplyResult_Suc);
                    }
                    else //if (diff < min)
                    {
                        result = Apply.ApplyResult_Fail;
                        MGame.instance.MUser.AddApply(Id, Apply.ApplyResult_Fail);
                    }
                }*/
            }

            if (this.panel)
            {
                this.panel.RefreshMsg((int)Id,result,refuseReason);
                //this.panel.Init(GetCandidatesListVCData(MGame.instance.MUser));
            }
            if( result == Apply.ApplyResult_Suc)
            {
                MGame.instance.MUser.AddDialogue(Id, MGame.instance.MUser.id,"I have accepted your application!", UnityFunctions.GetTimeStampSeconds());
                
                MGame.instance.ShowNoticePanelWithTwoBtn("Successfully applied! Talk to her right now?", () =>
                {
                    var view = this.parentNav.LoadDisplay<ChatListViewController>();
                    var viewCData = ChatListViewController.GetVCData(MGame.instance.MUser);
                    view.Init(viewCData);
                    
                },null);
            } 
            else if( result == Apply.ApplyResult_Fail)
            {
                string content = "";
                string confirmStr = "";
                string cancelStr = "Give Up";
                if (unreachTypes.Contains(FiveDimensionsType.Height))
                {
                    content = "The application was not successful, the given reason is Height not meeting the requirement";
                    confirmStr = "Increase height and date with her";
                }
                /*else if (unreachTypes.Contains(FiveDimensionsType.Weight))
                {
                    content = "The application was not successful, the given reason is Weight not meeting the requirement";
                    confirmStr = "Increase weight and date with her";
                }*/
                else if (unreachTypes.Contains(FiveDimensionsType.Income))
                {
                    content = "The application was not successful, the given reason is Income not meeting the requirement";
                    confirmStr = "Increase income and date with her";
                }
                else if (unreachTypes.Contains(FiveDimensionsType.Edu))
                {
                    content = "The application was not successful, the given reason is Education not meeting the requirement";
                    confirmStr = "Increase Edu and date with her";
                }
                
                MGame.instance.ShowNoticePanelWithTwoBtn(content,
                    () =>
                    {
                        var improve = this.parentNav.LoadDisplay<ImproveViewController>();
                        var improveVCData = ImproveViewController.GetImproveVCData(MGame.instance.MUser);
                        improve.Init(improveVCData);
                        MGame.instance.MUser.AddCoin(+applyPrice / 2);
                    },
                    () =>
                    {
                        MGame.instance.MUser.AddCoin(+applyPrice / 2);
                    },confirmStr,cancelStr);

            }
        });
    }

    public override void WillHideView()
    {
        base.WillHideView();

        if (m_Panel)
        {
            m_Panel.PlayHideAnim();
        }

        this.battleScene.ShowNormalCam();
    }

    void ChangePlayerCandidate(long skinId,bool temp)
    {
        battleScene.OnUpdateRole((int)skinId);
    }

    public override void OnViewDelete()
    {
        base.OnViewDelete();

        if (m_Panel)
        {
            Destroy(m_Panel.gameObject);
        }
        m_Panel = null;
    }

    public void OnBuy()
    {
        var skin = ConstantData.instance.GetCandidate(battleScene.skinId);
        if (skin != null)
        {
            int price = skin.price;

            if(MGame.instance.user.coin >= price)
            {
                /*bool suc = MGame.instance.MUser.AddCandidate(battleScene.skinId);
                if (suc)
                {
                    var data = this.m_Data.skins.Find(e => e.skinId == battleScene.skinId);
                    data.unlock = true;
                    m_Panel.UpdateCandidate(data);

                    GameDebug.Log($"buy skin suc");
#if GameAnalytics
                    GameAnalyticsSDK.GameAnalytics.NewDesignEvent($"Buy_Candidate_{m_CurCandidateId}");
#endif
                }*/
            }
            else
            {
                MGame.instance.ShowNoticePanel(Localization.instance.GetValue("coin_not_enough"));
            }

        }
    }
    public static CandidatesListVCData GetCandidatesListVCData(MGameUser gameUser)
    {
        CandidatesListVCData skinsListVCData = new CandidatesListVCData();
        skinsListVCData.candidates = ConstantData.instance.candidates.Map(e =>
        {
            CandidateVCData skinData = new CandidateVCData();

            skinData.candidateId = e.candidateId;
            skinData.price = e.price;
            skinData.unlock = true;
            skinData.name = e.name;
            skinData.location = e.location;
            skinData.job = e.job;
            skinData.fiveDimensions = e.fiveDimensions;
            skinData.require = e.requirement;
            var apply = gameUser.applies.Find(app => app.targetUserId == e.candidateId);
            if (apply != null)
            {
                skinData.result = apply.result;
            }
            /*if (e.skinId == ConstantData.defaultCandidate || gameUser.IsCandidateUnlock(e.skinId))
            {
                skinData.unlock = true;
            }
            else
            {
                skinData.unlock = false;
            }*/
            return skinData;
        }).AsList();

        /*int skinId = gameUser.curRoleId;
        if (skinId <= 0)
            skinId = ConstantData.defaultCandidate;*/

        //skinsListVCData.defaultCandidate = skinId;

        return skinsListVCData;
    }
}